package com.qqt.csr.order.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.qqt.csr.common.enums.DeletedEnum;
import com.qqt.csr.common.session.SessionContextHolder;
import com.qqt.csr.message.event.intrasite.IntraSiteMessageEventPublisher;
import com.qqt.csr.message.event.intrasite.workorder.WorkOrderEventSource;
import com.qqt.csr.order.assembler.OrderDynamicAssembler;
import com.qqt.csr.order.entity.WorkOrder;
import com.qqt.csr.order.enums.DynamicType;
import com.qqt.csr.order.enums.WorkOrderTemplateType;
import com.qqt.csr.order.vo.resp.OrderDynamicRespVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qqt.csr.order.mapper.OrderDynamicMapper;
import com.qqt.csr.order.entity.OrderDynamic;

@Slf4j
@Service
public class OrderDynamicService extends ServiceImpl<OrderDynamicMapper, OrderDynamic> {

    @Autowired
    private WorkOrderService workOrderService;

    @Autowired
    private IntraSiteMessageEventPublisher intraSiteMessageEventPublisher;

    public int updateBatch(List<OrderDynamic> list) {
        return baseMapper.updateBatch(list);
    }
    
    public int updateBatchSelective(List<OrderDynamic> list) {
        return baseMapper.updateBatchSelective(list);
    }
    
    public int batchInsert(List<OrderDynamic> list) {
        return baseMapper.batchInsert(list);
    }

    /**
     * 删除动态
     * @param id {@link Long} 动态id
     * @return {@link Boolean} 删除结果
     */
    public boolean deleteById(long id) {
        OrderDynamic dynamic = getById(id);
        // 校验动态类型
        if (DynamicType.MESSAGE_REPLY.getValue() == dynamic.getType()) {
            return removeById(id);
        }
        // 工单变更类型动态不支持删除
        log.warn("工单动态类型为【{}】，不支持删除", DynamicType.ORDER_CHANGES.getValue());
        return false;
    }

    /**
     * 评论工单
     * @param orderId {@link Long} 工单id
     * @param content {@link String} 评论内容
     * @return {@link Boolean} 评论结果
     */
    public boolean comments(long orderId, String content) {
        WorkOrder workOrder = workOrderService.getById(orderId);
        // 校验工单
        if (workOrder == null) {
            log.warn("工单不存在，工单id为【{}】", orderId);
            return false;
        }
        // 评论
        OrderDynamic comment = OrderDynamic.builder()
                .content(content)
                .orderId(orderId)
                .creatorId(SessionContextHolder.getHeaderInfo().getUserId())
                .type(DynamicType.MESSAGE_REPLY.getValue())
                .build();
        // 发送消息
        sendMessage(workOrder.getId(), workOrder.getTitle(), workOrder.getCreatorId(), workOrder.getDesigneeId());
        return save(comment);
    }

    /**
     * 回复评论
     * @param dynamicId {@link Long} 动态id
     * @param content {@link String} 回复内容
     * @return {@link Boolean} 回复结果
     */
    public boolean commentsReply(long dynamicId, String content) {
        OrderDynamic dynamic = getById(dynamicId);
        WorkOrder workOrder = workOrderService.getById(dynamic.getOrderId());
        // 校验动态类型
        if (DynamicType.MESSAGE_REPLY.getValue() == dynamic.getType()) {
            // 评论回复
            OrderDynamic reply = OrderDynamic.builder()
                    .content(content)
                    .parentId(dynamicId)
                    .orderId(dynamic.getOrderId())
                    .creatorId(SessionContextHolder.getHeaderInfo().getUserId())
                    .type(DynamicType.MESSAGE_REPLY.getValue())
                    .build();
            // 保存回复
            return save(reply);
        }
        // 发送消息
        sendMessage(workOrder.getId(), workOrder.getTitle(), workOrder.getCreatorId(), workOrder.getDesigneeId());
        log.warn("工单动态类型为【{}】，不支持回复", DynamicType.ORDER_CHANGES.getValue());
        return false;
    }

    /**
     * 查询工单动态
     * @param orderId {@link Long} 工单id
     * @return {@link List<OrderDynamicRespVO>} 工单动态响应
     */
    public List<OrderDynamicRespVO> list(long orderId) {
        // 查询动态
        List<OrderDynamic> list = listByOrderId(orderId);
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        // 获取父级动态id
        List<Long> parentIds = list.stream()
                // 动态类型为评论回复
                .filter(dynamic -> dynamic.getType() == DynamicType.MESSAGE_REPLY.getValue())
                .map(OrderDynamic::getParentId)
                // 去空
                .filter(Objects::nonNull)
                .toList();
        // 若父级动态为空，则直接返回
        if (parentIds.isEmpty()) {
            return BeanUtil.copyToList(list, OrderDynamicRespVO.class);
        }
        // 获取父级动态
        List<OrderDynamic> parentDynamics = listByIds(parentIds);
        return OrderDynamicAssembler.convert(list, parentDynamics);
    }

    /**
     * 根据工单id查询动态列表
     * @param orderId {@link Long} 工单id
     * @return {@link List<OrderDynamic>} 动态列表
     */
    public List<OrderDynamic> listByOrderId(long orderId) {
        LambdaQueryWrapper<OrderDynamic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDynamic::getOrderId, orderId);
        wrapper.eq(OrderDynamic::getDeleteFlag, DeletedEnum.NOT_DELETED.getCode());
        wrapper.orderByDesc(OrderDynamic::getCreateTime);
        return list(wrapper);
    }

    /**
     * 构建工单消息源
     * @param orderId {@link Long} 工单id
     * @param workOrderName {@link String} 工单名称
     * @param creatorId {@link Long} 创建人
     * @param processorId {@link Long} 处理人
     */
    private void sendMessage(Long orderId, String workOrderName, Long creatorId, Long processorId) {
        Long currentUserId = SessionContextHolder.getHeaderInfo().getUserId();
        List<Long> recipientIds = Lists.newArrayList(processorId);
        // 若当前用户不为创建人, 则加入创建人为接收人
        if (!currentUserId.equals(creatorId)) {
            recipientIds.add(creatorId);
        }
        // 若当前用户不为处理人, 则加入处理人为接收人
        if (!currentUserId.equals(processorId)) {
            recipientIds.add(processorId);
        }
        // 若接收人为空, 则不发送消息
        if (recipientIds.isEmpty()) {
            return;
        }
        // 构建消息参数
        Object[] params = new Object[]{SessionContextHolder.getHeaderInfo().getNickName()};
        WorkOrderEventSource source = WorkOrderEventSource.builder()
                .workOrderId(orderId)
                .workOrderName(workOrderName)
                .eventType(WorkOrderTemplateType.COMMENT_WORK_ORDER)
                .params(params)
                .recipientIds(recipientIds)
                .build();
        // 发送消息
        intraSiteMessageEventPublisher.publishEvent(source);
    }

}
